import { createRouter, createWebHistory } from 'vue-router'
import { getToken, removeToken } from '@/utils/auth'
import { useMenuStore } from '@/store/modules/useMenu'

/**
 * 自动加载 router 目录下的 index.ts 文件， 自动注入路由
 */
let routers: any = []
const routerContext = import.meta.glob('./*/*.ts', { eager: true }) // eager: true, 直接导入所有模块，import.meta,glob() 默认懒加载
Object.keys(routerContext).forEach((route) => {
  if (route.startsWith('./index')) {
    return
  }
  const routerModule: any = routerContext[route]
  routers = [...routers, ...(routerModule.default || routerModule)]
})

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/layout/index.vue'),
      children: [...routers]
    }
  ]
})

/**
 * 路由前置守卫
 */
router.beforeEach((to, from, next) => {
  const token = getToken() && JSON.parse(getToken()!)
  const menuState = useMenuStore()

  // 不需要校验token白名单列表
  const whiteList: string[] = ['/login']
  if (to.meta.title) {
    document.title = to.meta.title as string
  }
  if (token?.token) {
    menuState.addMenu()
    next()
  } else if (!token?.token && whiteList.indexOf(to.path) === -1) {
    router.push('/login')
    menuState.removeMenu()
    next()
  } else {
    next()
  }
  if (to.path === '/login') {
    menuState.removeMenu()
    removeToken()
  }
})

export default router
